// pages/index/login.js
var util = require('../../utils/util.js');
var app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: '',
    openId: '',
    inputName: '',
    inputCode: '',
    codeValue: '获取验证码',
    timer: '', //定时器名字
    second: 60 //倒计时初始值  秒数:60s
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '登录'
    })
    
  },

  /**
   * 登录
   */
  loginClick: function() {
    var that = this;
    var inputName = that.data.inputName
    var inputCode = that.data.inputCode
    var message = ''
    if (inputCode.length == 0) {
      message = '请输入验证码!'
    }
    if (inputName.length == 0) {
      message = '请输入手机号!'
    }
    if (message.length > 0) {
      wx.showToast({
        title: message,
        icon: 'none'
      })
      return
    }
    
    var openId = util.user.openid;
    //绑定手机号
    var params = {
      phone: inputName,
      phone_code: inputCode,
      openid: openId
    }
    util.POST(util.URL.phone_bind, params, function(sData) {
      var userInfo= util.user;
      userInfo.phone = inputName
      util.user=userInfo;
      wx.navigateBack();

    }, function(eData) {
      wx.showToast({
        title: eData.msg,
        icon: 'none'
      });
    })
  },
  /**
   * 手动输入
   */
  textInput: function(e) {
    var that = this;
    var inputId = e.currentTarget.id;
    var inputValue = e.detail.value;
    //账号
    if (inputId == 1) {
      that.setData({
        inputName: inputValue
      })
    }
    //密码
    if (inputId == 2) {
      that.setData({
        inputCode: inputValue
      })
    }
  },

  /**
   * 获取验证码
   */
  codeClick: function() {
    var that = this;
    var phone = that.data.inputName
    if (phone.length != 11) {
      wx.showToast({
        title: '请输入手机号!',
        icon: 'none'
      });
    } else {
      var params = {
        phone: phone
      }
      util.POST(util.URL.phone_code, params, function(sData) {
        that.getCountdown();
      }, function(eData) {
        wx.showToast({
          title: eData.msg,
          icon: 'none'
        });
      });
    }
  },

  /**
   * 倒计时
   */
  getCountdown: function() {
    var that = this;
    var second = that.data.second; //秒数:60s
    var interval = setInterval(function() {
      second--;
      if (second > 0) {
        that.setData({
          codeValue: '剩余' + second + '秒'
        });
      } else {
        that.setData({
          codeValue: '获取验证码'
        });
      }
    }.bind(that), 1000);

    that.setData({
      timer: interval
    });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    if (util.user && util.user.phone.length<=0) {
      //未成功登录
      var userInfo=util.user;
      userInfo.ishome=true;
      util.user=userInfo;
    }
  }
})